/**
 * Copyright (C) 2010-2013 Alibaba Group Holding Limited
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package com.alibaba.rocketmq.example.transaction;

import java.util.concurrent.atomic.AtomicInteger;

import com.alibaba.rocketmq.client.producer.LocalTransactionState;
import com.alibaba.rocketmq.client.producer.TransactionCheckListener;
import com.alibaba.rocketmq.common.message.MessageExt;


/**
 * 长期未回复的prepare的消息,broker回查producer
 
 * 自定义业务类，该类实现TransactionCheckListener接口的checkLocalTransactionState(final MessageExt msg)方法，
 * 该方法是对于本地业务执行完毕之后发送事务消息状态时失败导致Broker端的事务消息一直处于PREPARED状态的补救(小概率事件)，
 * 在Broker启动TransactionStateService时，为每个tranStateTable文件创建了一个定时任务，该定时任务是每隔1分钟遍历一遍文件中的所有消息，
 * Broker对于长期处于PREPARED状态的事务消息发起回查请求时，Producer在收到回查事务消息状态请求之后，
 * 调用该checkLocalTransactionState方法，该方法的请求参数是之前发送的事务消息，
 * 在该方法中根据此前发送的事务消息来检查该消息对应的本地业务逻辑处理的情况(自己写代码判断之前该消息对应的本地事务是成功还是失败)，
 * 根据处理情况告知Broker该事务消息的最终状态commit或者rollback
 * 

 */
public class TransactionCheckListenerImpl implements TransactionCheckListener {
    private AtomicInteger transactionIndex = new AtomicInteger(0);


    @Override
    public LocalTransactionState checkLocalTransactionState(MessageExt msg) {
        System.out.println("server checking TrMsg " + msg.toString());

        int value = transactionIndex.getAndIncrement();
        if ((value % 6) == 0) {
            throw new RuntimeException("Could not find db");
        }
        else if ((value % 5) == 0) {
            return LocalTransactionState.ROLLBACK_MESSAGE;
        }
        else if ((value % 4) == 0) {
            return LocalTransactionState.COMMIT_MESSAGE;
        }

        return LocalTransactionState.UNKNOW;
    }
}
